<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\validate;


use app\index\model\Order;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Validate;

class EvaluateValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名'    =>    ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'remake' => 'max:250',
        'reply' => 'max:300',
        'id' => 'require|number',
        'evaluate' => 'require|checkEvaluate',
        'source' => 'require'
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名'    =>    '错误信息'
     *
     * @var array
     */
    protected $message = [
        'remake.max' => '备注最多字数不超过250',
        'reply.max' => '回复最多字数不超过300',
        'id.require' => '订单ID必须传',
        'id.number' => '订单ID必须是数字',
        'evaluate.require' => '评论内容必传',
        'source.require' => '来源必传'
    ];

    protected $scene = [
        'examine' => ['remake'],
        'reply' => ['reply'],
        'evaluate' => ['id', 'evaluate', 'source']
    ];

    protected function checkEvaluate($value, $rule, $data = [])
    {
        $arr = json_decode($value, true);
        foreach ($arr as $v) {
            if (count($v['img_urls'])>5 ) return "图片不能超过5张";
            if(strlen($v['content'])>250) return "评论内容字数不能超过250字";
            if(empty($v['content'])) return "评论内容不能为空";
            if(empty($v['score']) || !is_numeric($v['score'])) return "评分不能为空,不能非数字";
        }
        return true;
    }

    /**数据权限校验
     * @param int $oid
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function checkCurrentUser($value, $rule, $data=[])
    {
        global $user;
        $order = Order::find($value);
        if ($user['id'] != $order['user_id']) return $rule = "您无权查看...";
    }
}